package com.collage.ctrl;

import com.collage.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "文件上传接口集")
@RestController
@RequestMapping("file")
public class FileController {
    @Value("${file-upload-path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public Result uploadFile(@RequestParam("file")MultipartFile file) {
        if (null == file || file.isEmpty()) {
            return Result.failed("文件为空");
        }
        File pathFile = new File(fileUploadPath);
        if (!pathFile.exists()) {
            pathFile.mkdir();
        }
        String newFileName = UUID.randomUUID().toString() + (file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")));
        String path = fileUploadPath + newFileName;
        File newFile = new File(path);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(newFileName);
    }
}
